<?php

/**
 * 职位管理类
 * 处理职位的增删改查操作
 */
class Position {
    private $conn;
    private $auth;

    public function __construct(PDO $conn, Auth $auth) {
        $this->conn = $conn;
        $this->auth = $auth;
    }

    /**
     * 获取职位列表 (需要管理员权限)
     * @method GET
     * @route /position/list
     */
    public function list(): void {
        $this->auth->checkAdmin();
        
        // 获取当前登录用户信息
        $currentUserId = $this->auth->getUserId();
        $stmt = $this->conn->prepare("SELECT permission, company_id FROM users WHERE id = :id LIMIT 1");
        $stmt->execute([':id' => $currentUserId]);
        $currentUser = $stmt->fetch(PDO::FETCH_ASSOC);
        
        $page = max(1, intval($_GET['page'] ?? 1));
        $pageSize = min(50, max(10, intval($_GET['pageSize'] ?? 20)));
        $offset = ($page - 1) * $pageSize;

        // 构建查询条件
        $where = [];
        $params = [];
        
        // 非超级管理员只能查看自己公司的职位
        if ($currentUser['permission'] !== 'superadmin') {
            if ($currentUser['company_id'] === null) {
                $where[] = "company_id IS NULL";
            } else {
                $where[] = "company_id = :company_id";
                $params[':company_id'] = $currentUser['company_id'];
            }
        }
        
        if (!empty($_GET['keyword'])) {
            $keyword = '%' . $_GET['keyword'] . '%';
            $where[] = "name LIKE :keyword";
            $params[':keyword'] = $keyword;
        }

        if (isset($_GET['status']) && $_GET['status'] !== '') {
            $where[] = "status = :status";
            $params[':status'] = intval($_GET['status']);
        }

        $whereClause = $where ? 'WHERE ' . implode(' AND ', $where) : '';

        // 查询总数
        $stmt = $this->conn->prepare("SELECT COUNT(*) FROM positions {$whereClause}");
        $stmt->execute($params);
        $total = $stmt->fetchColumn();

        // 查询数据
        $stmt = $this->conn->prepare("            SELECT id, name, status, parent_id, company_id, created_at, updated_at            FROM positions            {$whereClause}            ORDER BY id DESC            LIMIT :offset, :limit        ");
        $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
        $stmt->bindValue(':limit', $pageSize, PDO::PARAM_INT);
        
        foreach ($params as $key => $value) {
            $stmt->bindValue($key, $value);
        }
        
        $stmt->execute();
        $list = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // 返回列表数据
        echo json_encode([
            'code' => 200,
            'data' => [
                'list' => $list,
                'pagination' => [
                    'total' => $total,
                    'page' => $page,
                    'pageSize' => $pageSize,
                    'totalPages' => ceil($total / $pageSize)
                ]
            ]
        ]);
    }

    /**
     * 获取所有启用的职位 (用于下拉选择)
     * @method GET
     * @route /position/all
     */
    public function all(): void {
        // 尝试获取用户信息，但如果没有token或token无效也不阻止访问（前台可能用得到）
        $userInfo = null;
        try {
            $token = $this->auth->getBearerToken();
            $userInfo = $this->auth->validateToken($token);
        } catch (Exception $e) {
            // 没有有效的token，继续执行，返回所有职位
        }
        
        // 根据用户权限和职位构建查询条件
        $where = 'status = 1';
        $params = [];
        
        // 如果有有效的用户信息，根据用户权限和公司过滤职位
        if ($userInfo) {
            $userPermission = $userInfo['permission'];
            $userCompanyId = $userInfo['company_id'];
            
            // 非超级管理员只能查看自己公司的职位
            if ($userPermission !== 'superadmin') {
                if ($userCompanyId === null) {
                    $where .= " AND company_id IS NULL";
                } else {
                    $where .= " AND company_id = :company_id";
                    $params[':company_id'] = $userCompanyId;
                }
            }
        }
        
        // 原有的基于职位的过滤逻辑保留，但会与基于公司的过滤结合
        if ($userInfo) {
            $userPermission = $userInfo['permission'];
            $userPosition = $userInfo['position'];
            // 超级管理员已经在前面处理过了，这里只处理admin和member权限
            
            // 超级管理员可以查看所有职位
            if ($userPermission === 'superadmin') {
                // 不需要额外过滤
            }
            // 管理员可以查看所在公司的所有职位
            else if ($userPermission === 'admin') {
                // 不需要额外的职位过滤，因为已经通过company_id过滤了
                // 管理员应该能够查看和管理自己公司的所有职位
            }
            // 普通用户只能看到自己的职位
            else if ($userPermission === 'member' && !empty($userPosition)) {
                $where .= " AND name = :position";
                $params[':position'] = $userPosition;
            }
        }
        
        $stmt = $this->conn->prepare(
            "
            SELECT id, name
            FROM positions
            WHERE {$where}
            ORDER BY id DESC
            "
        );

        // 绑定参数
        foreach ($params as $param => $value) {
            $stmt->bindValue($param, $value, PDO::PARAM_STR);
        }
        
        $stmt->execute();
        $positions = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        // 转换为前端需要的格式 {value, text}
        $list = [];
        foreach ($positions as $position) {
            $list[] = [
                'value' => $position['id'],
                'text' => $position['name']
            ];
        }
        
        // 不再添加额外的空选项，前端通过placeholder="请选择职位"来显示提示文本
        
        echo json_encode([
            'code' => 200,
            'data' => $list
        ]);
    }

    /**
     * 创建职位 (需要管理员权限)
     * @method POST
     * @route /position/create
     */
    public function create(): void {
        // 允许管理员和超级管理员创建职位
        $currentUserId = $this->auth->getUserId();
        $stmt = $this->conn->prepare("SELECT permission, company_id FROM users WHERE id = :id LIMIT 1");
        $stmt->execute([':id' => $currentUserId]);
        $currentUser = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($currentUser['permission'] !== 'admin' && $currentUser['permission'] !== 'superadmin') {
            throw new Exception("没有权限创建职位", 403);
        }
        
        $data = json_decode(file_get_contents('php://input'), true);
        
        // 验证必填字段
        if (empty($data['name'])) {
            throw new Exception("职位名称不能为空", 400);
        }

        // 检查职位名称是否已存在
        $stmt = $this->conn->prepare("SELECT id FROM positions WHERE name = :name LIMIT 1");
        $stmt->execute([':name' => $data['name']]);
        if ($stmt->fetch()) {
            throw new Exception("职位名称已存在", 409);
        }

        $time = time();

        // 准备职位数据
        $positionData = [
            ':name' => $data['name'],
            ':status' => $data['status'] ?? 1,
            ':company_id' => $currentUser['company_id'],
            ':created_at' => $time,
            ':updated_at' => $time
        ];

        // 处理父职位ID
        $fields = "name, status, company_id, created_at, updated_at";
        $values = ":name, :status, :company_id, :created_at, :updated_at";
        
        if (isset($data['parent_id']) && $data['parent_id'] !== '') {
            // 验证父职位是否存在
            $stmt = $this->conn->prepare("SELECT id FROM positions WHERE id = :parent_id");
            $stmt->execute([':parent_id' => $data['parent_id']]);
            if ($stmt->fetch()) {
                $positionData[':parent_id'] = $data['parent_id'];
                $fields .= ", parent_id";
                $values .= ", :parent_id";
            }
        }

        // 插入职位数据
        $stmt = $this->conn->prepare("INSERT INTO positions ($fields) VALUES ($values)");

        if (!$stmt->execute($positionData)) {
            throw new Exception("创建职位失败", 500);
        }

        $positionId = $this->conn->lastInsertId();

        // 返回创建成功信息
        echo json_encode([
            'code' => 200,
            'msg' => '创建成功',
            'data' => [
                'position_id' => $positionId
            ]
        ]);
    }

    /**
     * 更新职位信息 (需要管理员权限)
     * @method POST
     * @route /position/update
     */
    public function update(): void {
        // 允许管理员和超级管理员更新职位
        $currentUserId = $this->auth->getUserId();
        $stmt = $this->conn->prepare("SELECT permission, company_id FROM users WHERE id = :id LIMIT 1");
        $stmt->execute([':id' => $currentUserId]);
        $currentUser = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($currentUser['permission'] !== 'admin' && $currentUser['permission'] !== 'superadmin') {
            throw new Exception("没有权限更新职位", 403);
        }
        
        $data = json_decode(file_get_contents('php://input'), true);
        
        // 验证必填字段
        if (empty($data['id'])) {
            throw new Exception("缺少职位ID", 400);
        }

        // 检查职位是否存在
        $stmt = $this->conn->prepare("SELECT id, company_id FROM positions WHERE id = :id LIMIT 1");
        $stmt->execute([':id' => $data['id']]);
        $position = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$position) {
            throw new Exception("职位不存在", 404);
        }
        
        // 非超级管理员只能更新自己公司的职位
        if ($currentUser['permission'] !== 'superadmin' && $position['company_id'] !== $currentUser['company_id']) {
            throw new Exception("只能更新自己公司的职位", 403);
        }

        // 构建更新字段
        $updateFields = [];
        $params = [':id' => $data['id']];

        // 更新职位名称
        if (!empty($data['name'])) {
            // 检查职位名称是否已被其他职位使用
            $stmt = $this->conn->prepare("SELECT id FROM positions WHERE name = :name AND id != :id LIMIT 1");
            $stmt->execute([':name' => $data['name'], ':id' => $data['id']]);
            if ($stmt->fetch()) {
                throw new Exception("职位名称已被其他职位使用", 409);
            }
            
            $updateFields[] = "name = :name";
            $params[':name'] = $data['name'];
        }

        // 更新状态
        if (isset($data['status'])) {
            $updateFields[] = "status = :status";
            $params[':status'] = intval($data['status']);
        }

        // 更新父职位ID
        if (isset($data['parent_id'])) {
            if ($data['parent_id'] === '') {
                // 设置为顶级职位
                $updateFields[] = "parent_id = NULL";
            } else {
                // 验证父职位是否存在且不是当前职位自身
                if ($data['parent_id'] == $data['id']) {
                    throw new Exception("不能将职位设置为自身的父职位", 400);
                }
                
                $stmt = $this->conn->prepare("SELECT id FROM positions WHERE id = :parent_id");
                $stmt->execute([':parent_id' => $data['parent_id']]);
                if ($stmt->fetch()) {
                    $updateFields[] = "parent_id = :parent_id";
                    $params[':parent_id'] = $data['parent_id'];
                } else {
                    throw new Exception("父职位不存在", 404);
                }
            }
        }

        // 更新时间
        $updateFields[] = "updated_at = :updated_at";
        $params[':updated_at'] = time();

        if (count($updateFields) <= 1) { // 只有updated_at字段
            throw new Exception("没有可更新的字段", 400);
        }

        // 执行更新
        $sql = "UPDATE positions SET " . implode(', ', $updateFields) . " WHERE id = :id";
        $stmt = $this->conn->prepare($sql);
        
        if (!$stmt->execute($params)) {
            throw new Exception("更新职位信息失败", 500);
        }

        // 返回成功信息
        echo json_encode([
            'code' => 200,
            'msg' => '更新成功'
        ]);
    }

    /**
     * 删除职位 (需要管理员权限)
     * @method POST
     * @route /position/delete
     */
    public function delete(): void {
        // 允许管理员和超级管理员删除职位
        $currentUserId = $this->auth->getUserId();
        $stmt = $this->conn->prepare("SELECT permission, company_id FROM users WHERE id = :id LIMIT 1");
        $stmt->execute([':id' => $currentUserId]);
        $currentUser = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($currentUser['permission'] !== 'admin' && $currentUser['permission'] !== 'superadmin') {
            throw new Exception("没有权限删除职位", 403);
        }
        
        $data = json_decode(file_get_contents('php://input'), true);
        
        // 验证必填字段
        if (empty($data['id'])) {
            throw new Exception("缺少职位ID", 400);
        }

        // 检查职位是否存在
        $stmt = $this->conn->prepare("SELECT id, company_id FROM positions WHERE id = :id LIMIT 1");
        $stmt->execute([':id' => $data['id']]);
        $position = $stmt->fetch(PDO::FETCH_ASSOC);
        if (!$position) {
            throw new Exception("职位不存在", 404);
        }
        
        // 非超级管理员只能删除自己公司的职位
        if ($currentUser['permission'] !== 'superadmin' && $position['company_id'] !== $currentUser['company_id']) {
            throw new Exception("只能删除自己公司的职位", 403);
        }

        // 检查是否有用户正在使用该职位
        $stmt = $this->conn->prepare("SELECT id FROM users WHERE position = (SELECT name FROM positions WHERE id = :id) LIMIT 1");
        $stmt->execute([':id' => $data['id']]);
        if ($stmt->fetch()) {
            throw new Exception("该职位已有用户使用，无法删除", 400);
        }

        // 执行删除
        $stmt = $this->conn->prepare("DELETE FROM positions WHERE id = :id");
        
        if (!$stmt->execute([':id' => $data['id']])) {
            throw new Exception("删除职位失败", 500);
        }

        // 返回成功信息
        echo json_encode([
            'code' => 200,
            'msg' => '删除成功'
        ]);
    }
}